"""
企业混合App后端API - FastAPI实现
基于文档规范构建的完整Web API服务
"""

from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
import uvicorn
import logging
import time
import os

from config import get_settings
from database import engine, Base, init_sample_data
from models.common import StandardResponse
from routers import (
    auth_router, system_router, home_router, apps_router,
    workspace_router, messages_router, user_router, upload_router
)

# 获取配置
settings = get_settings()

# 配置日志
logging.basicConfig(
    level=getattr(logging, settings.log_level),
    format=settings.log_format
)
logger = logging.getLogger(__name__)

# 创建数据库表
Base.metadata.create_all(bind=engine)

# 初始化示例数据
init_sample_data()

# 创建FastAPI应用
app = FastAPI(
    title=settings.app_name,
    description="基于FastAPI构建的企业移动办公平台后端服务",
    version=settings.app_version,
    docs_url="/docs" if settings.debug else None,
    redoc_url="/redoc" if settings.debug else None
)

# CORS中间件配置
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.allowed_origins,
    allow_credentials=True,
    allow_methods=settings.allowed_methods,
    allow_headers=settings.allowed_headers,
)

# 静态文件服务
if not os.path.exists(settings.upload_dir):
    os.makedirs(settings.upload_dir, exist_ok=True)

app.mount("/uploads", StaticFiles(directory=settings.upload_dir), name="uploads")

# 请求日志中间件
@app.middleware("http")
async def log_requests(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    
    logger.info(
        f"{request.method} {request.url.path} - "
        f"Status: {response.status_code} - "
        f"Time: {process_time:.4f}s"
    )
    return response

# 注册路由
app.include_router(auth_router, prefix="/api")
app.include_router(system_router, prefix="/api")
app.include_router(home_router, prefix="/api")
app.include_router(apps_router, prefix="/api")
app.include_router(workspace_router, prefix="/api")
app.include_router(messages_router, prefix="/api")
app.include_router(user_router, prefix="/api")
app.include_router(upload_router, prefix="/api")

# 根路径
@app.get("/", response_model=StandardResponse)
async def root():
    """根路径"""
    return StandardResponse(
        success=True,
        message=f"{settings.app_name}服务运行正常",
        data={
            "version": settings.app_version,
            "status": "running",
            "environment": "development" if settings.debug else "production"
        }
    )

# 扫码相关接口（保留原有功能）
@app.get("/api/qr/scan/{qr_code}", response_model=StandardResponse)
async def scan_qr_code(qr_code: str):
    """扫码处理"""
    # 模拟不同类型的二维码处理
    qr_data = {
        "TEST001": {
            "type": "equipment",
            "name": "设备001",
            "location": "A栋1楼",
            "status": "正常",
            "lastMaintenance": "2024-01-10"
        },
        "USER002": {
            "type": "user",
            "name": "李四",
            "department": "技术部",
            "position": "工程师",
            "phone": "13800138002"
        },
        "DOC003": {
            "type": "document",
            "title": "项目计划书",
            "version": "v1.2",
            "author": "项目组",
            "updateTime": "2024-01-12"
        }
    }
    
    result = qr_data.get(qr_code)
    if not result:
        return StandardResponse(
            success=False,
            message="无效的二维码",
            error="二维码不存在或已过期"
        )
    
    return StandardResponse(
        success=True,
        message="扫码成功",
        data=result
    )

# 错误处理
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
    """HTTP异常处理"""
    return JSONResponse(
        status_code=exc.status_code,
        content=StandardResponse(
            success=False,
            message=exc.detail,
            error=f"HTTP {exc.status_code}",
            timestamp=int(time.time())
        ).dict()
    )

@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
    """通用异常处理"""
    logger.error(f"Unhandled exception: {exc}")
    return JSONResponse(
        status_code=500,
        content=StandardResponse(
            success=False,
            message="服务器内部错误",
            error="Internal Server Error",
            timestamp=int(time.time())
        ).dict()
    )

if __name__ == "__main__":
    uvicorn.run(
        "main:app",
        host=settings.host,
        port=settings.port,
        reload=settings.debug,
        log_level=settings.log_level.lower()
    )